/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.uwlaser.modules.quartz.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.uwlaser.modules.quartz.service.dto.BackUpParam;
import com.uwlaser.modules.system.service.SysLogsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Date;
import java.util.HashSet;

/**
 * 测试用
 * @author Zheng Jie
 * @date 2019-01-08
 */
@Slf4j
@Component
public class TestTask {

    private final SysLogsService sysLogsService;

    public TestTask(SysLogsService sysLogsService) {
        this.sysLogsService = sysLogsService;
    }

    public void run(){
        log.info("run 执行成功");
    }

    public void run1(String str){
        log.info("run1 执行成功，参数为： {}" + str);
    }

    public void run2(){
        System.out.println("----------------------");
        System.out.println("cron执行："+DateUtil.format(new Date(),"yyyy年MM月dd日-HH:mm:ss"));
        System.out.println("----------------------");
        log.info("run2 执行成功");
    }

    public void executeDbBack(String param){
        //对象转换
        BackUpParam backUpParam;
        try {
            backUpParam = JSONObject.parseObject(param, BackUpParam.class);
        } catch (Exception e){
            throw new RuntimeException("JSON转换对象时异常，请检查此定时任务的请求参数!");
        }

        System.out.println("参数对象："+JSONUtil.parseObj(backUpParam,false));

        //调用备份方法
        dbBackUp(backUpParam.getHost(),
                backUpParam.getUserName(),
                backUpParam.getPassword(),
                backUpParam.getPort(),
                backUpParam.getDbName(),
                backUpParam.getTableNameSets(),
                backUpParam.getBackUpPath());
    }

    public static void dbBackUp(String host, String userName, String password, String port, String dbName, HashSet<String> tableNameSets, String backupPath) {
        //创建当日备份文件夹
        String folderName= DateUtil.format(new Date(),"yyyyMMddHHmmss");
        //年份文件名
        String yearFolderName= DateUtil.format(new Date(),"yyyy");
        //月份文件名
        String monthFolderName= DateUtil.format(new Date(),"MM");
        //创建文件夹命令
        String createFolderCMD="cmd /c md"+" "+backupPath+yearFolderName+"\\"+monthFolderName+"\\"+folderName;
        System.out.println("文件夹创建CMD："+createFolderCMD);
        try {
            //执行创建文件夹命令
            Process createFolderResult = Runtime.getRuntime().exec(createFolderCMD);
            if(createFolderResult.waitFor()!=0){
                throw new RuntimeException("备份数据库异常：创建"+folderName+"文件夹失败，创建命令为【"+createFolderCMD+"】");
            }
            if(!CollectionUtils.isEmpty(tableNameSets)) { //按表备份
                //迭代需要备份的数据表
                for (String tableName : tableNameSets) {
                    //备份文件名时间戳
                    String dateFormat = DateUtil.format(new Date(),"yyyyMMddHHmmss");
                    //备份文件名
                    String fileName=dateFormat+"_"+tableName+".sql";
                    //备份cmd命令
                    String cmd = "mysqldump" +" -h"+host + " -P" + port + " -u" + userName + " -p" + password + " " + dbName+" "+tableName + " -r " +backupPath+yearFolderName+"\\"+monthFolderName+"\\"+folderName+"\\"+fileName;
                    System.out.println("备份cmd：" + cmd);
                    Process createBackFileResult = Runtime.getRuntime().exec(cmd);
                    if (createBackFileResult.waitFor() == 0) {
                        System.out.println("库："+dbName + "-表："+tableName+"备份成功!");
                    } else {
                        System.out.println("库："+dbName + "-表："+tableName+"备份失败!");
                    }
                }
            }else {//备份整个库
                //备份文件名时间戳
                String dateFormat = DateUtil.format(new Date(),"yyyyMMddHHmmss");
                //备份文件名
                String fileName=dateFormat+"_"+dbName+".sql";
                //备份cmd命令
                String cmd = "mysqldump" +" -h"+host + " -P" + port + " -u" + userName + " -p" + password + " " + dbName + " -r " +backupPath+yearFolderName+"\\"+monthFolderName+"\\"+folderName+"\\"+fileName;
                System.out.println("备份cmd：" + cmd);
                Process createBackFileResult = Runtime.getRuntime().exec(cmd);
                if (createBackFileResult.waitFor() == 0) {
                    System.out.println(dbName + "数据库备份成功!");
                } else {
                    System.out.println(dbName + "数据库备份失败!");
                }
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 定时清除操作日志
     * */
    public void executeClearLog(String saveDay){
        //对象转换
        try {
            sysLogsService.clearLog(saveDay);
        } catch (Exception e){
            throw new RuntimeException("定时清除日志发生异常!");
        }
    }


}


